﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SCFHS.Data;
using SCFHS.Code;
using System.Data;

namespace SCFHS.Views.Searchs
{
    public partial class FullOrder : SysBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                BindOnLoadControls();

            if (Session["resultOrder"] != null)
            {
                Order resultOrder = Session["resultOrder"] as Order;
                BindFullOrder(resultOrder);
            }
            else
            {
                Response.Redirect("search.aspx");
            }
        }
        protected void drpOrderState_DataBound(object sender, EventArgs e)
        {
            DropDownList drp = ((DropDownList)sender);
            drp.Items.Insert(0, new ListItem("يرجي الإختيار من القائمة", "-1"));
        }


        private void BindOnLoadControls()
        {
            List<ListItem> orderStates = new List<ListItem>();
            foreach (OrderStates item in Enum.GetValues(typeof(OrderStates)))
            {
                int orderStateCode = (int)item;
                ListItem lstItm = new ListItem(parseOrderStateAr(orderStateCode.ToString()), orderStateCode.ToString());
                orderStates.Add(lstItm);
            }

            drpOrderState.DataSource = orderStates;
            drpOrderState.DataValueField = "Value";
            drpOrderState.DataTextField = "Text";
            drpOrderState.DataBind();

            drpNationality.DataSource = controller.ListNationalities();
            BindDrps(drpNationality);

            drpCurrenCity.DataSource = controller.ListCities();
            BindDrps(drpCurrenCity);
        }

        void BindFullOrder(Order resultOrder)
        {
            if (order == null)
            {
                Response.Redirect("Search.aspx");
            }
            hdfOrderNo.Value = resultOrder.orderID.ToString();
            txtpersonName.Text = resultOrder.personName;
            txtOrderNumber.Text = resultOrder.orderNumber;
            txtDate.Text = resultOrder.CreationDate.ToShortDateString();
            lblCurrentOrderState.Text = parseOrderStateAr(((int)resultOrder.orderState).ToString());
            hdfCurrentOrderState.Value = ((int)resultOrder.orderState).ToString();
            if (resultOrder.orderState == OrderStates.ReadyTocomplete)
            {
                dvFullInfo.Visible = false;
                OrderAttachmentFiles.Visible = false;
                OrderSummery.Visible = false;
                OrderRequest.Visible = false;
                OrderAttachmens.Visible = false;
                OrderInstructions.Visible = false;
                return;
            }

            dvFullInfo.Visible = true;
            OrderAttachmentFiles.Visible = true;
            OrderSummery.Visible = true;
            OrderRequest.Visible = true;
            OrderAttachmens.Visible = true;

            //Order details info
            txtSubject.Text = resultOrder.orderSubject;
            ListItem itm = drpNationality.Items.FindByValue(resultOrder.personNationality.ToString());
            if (itm != null)
                drpNationality.SelectedValue = resultOrder.personNationality.ToString();
            else
                drpNationality.SelectedIndex = 0;
            itm = drpCurrenCity.Items.FindByValue(resultOrder.personCurrentResidencePlace.ToString());
            if (itm != null)
                drpCurrenCity.SelectedValue = resultOrder.personCurrentResidencePlace.ToString();
            else
                drpCurrenCity.SelectedIndex = 0;
            
            txtIDNumber.Text = resultOrder.personIDNumber;
            rdIDType.SelectedValue = resultOrder.personIDType.ToString();
            txtClass.Text = resultOrder.orderClassificationNumber;
            rdBirthPlace.SelectedValue = resultOrder.personBirthPlace.ToString();
            rdSecondrySchool.SelectedValue = resultOrder.personHighSchoolPlace.ToString();
            txtWorkPlace.Text = resultOrder.workPlaceName;
            rdWorkType.SelectedValue = resultOrder.workPlaceType.ToString();

            //Order Attachment files
            grdAttachmentFiles.DataSource = controller.ListAttachmentFiles(resultOrder.orderID, AttachmentsType.All);
            grdAttachmentFiles.DataBind();

            //Order summery
            grdSummery.DataSource = controller.ListFullSummeryPointsForOrder(resultOrder.orderID);
            grdSummery.DataBind();

            //Order Requests
            grdRequest.DataSource = controller.ListFullRequestPointsForOrder(resultOrder.orderID);
            grdRequest.DataBind();

            //Order attachmetn discriptions
            grdAttachments.DataSource = controller.ListAttachmentPoints(resultOrder.orderID);
            grdAttachments.DataBind();

            if (resultOrder.orderState <= OrderStates.Printed)
            {
                OrderInstructions.Visible = false;
                return;
            }
            //Order Instructions
            OrderInstructions.Visible = true;
            BindFollowupCatalog(resultOrder);

        }

        protected void btnUpdateOrderState_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(hdfOrderNo.Value))
            {
                return;
            }

            if (drpOrderState.SelectedValue == "-1" || drpOrderState.SelectedValue == hdfCurrentOrderState.Value)
            {
                return;
            }

            OrderStates newOrdrState = (OrderStates)int.Parse(drpOrderState.SelectedValue);
            try
            {
                bool result = controller.UpdateOrderStates(int.Parse(hdfOrderNo.Value), newOrdrState, user.userID);
                if (result)
                {
                    order = controller.SelectFullOrderInfo(int.Parse(hdfOrderNo.Value));
                    BindFullOrder(order);
                }
            }
            catch (Exception)
            {

                throw;
            }

        }
        protected void btnClosrOrder_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(hdfOrderNo.Value))
            {
                return;
            }

            try
            {
                bool result = controller.UpdateOrderStates(int.Parse(hdfOrderNo.Value), OrderStates.Closed, user.userID, true);
                if (result)
                {
                    order = controller.SelectFullOrderInfo(int.Parse(hdfOrderNo.Value));
                    BindFullOrder(order);
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        void BindDrps(DropDownList drp)
        {
            drp.DataTextField = "Name";
            drp.DataValueField = "ID";
            drp.DataBind();
        }

        void BindFollowupCatalog(Order order = null)
        {

            DataTable customDt = new DataTable();

            DataTable instructionDt = controller.ListInstructionsForOrder(order.orderID);
            if (instructionDt == null)
            {
                lblMessage.Text = Messages.GeneralError;
                lblMessage.CssClass = "error";
                return;
            }

            DataTable followupDt = controller.ListFollowupsForOrder(order.orderID);

            DataColumn clm = new DataColumn("Type");
            clm.DefaultValue = "Instruction";
            instructionDt.Columns.Add(clm);

            customDt = instructionDt.Clone();

            if (followupDt != null)
            {
                clm = new DataColumn("Type");
                clm.DefaultValue = "Followup";
                followupDt.Columns.Add(clm);
                customDt.Merge(followupDt.Clone());
            }

            customDt.Rows.Clear();

            for (int i = 0; i < instructionDt.Rows.Count; i++)
            {
                customDt.ImportRow(instructionDt.Rows[i]);
                if (i < followupDt.Rows.Count)
                    customDt.ImportRow(followupDt.Rows[i]);
            }
            rptFollowupdCatalog.DataSource = customDt;
            rptFollowupdCatalog.DataBind();
        }
    }
}